package com.fjzzct.report.utils;

import org.apache.commons.codec.binary.Base64;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

public class DomionHelper {

	public static boolean IsValidToken(String ltpaToken) throws Exception {
		String ltpaDominoSecret = "bBp+Td5M0RlzH4lwOD77ev3LHlk=";
		final String CHARSET = "Cp850";		
		byte[] dominoSecret = Base64.decodeBase64(ltpaDominoSecret.getBytes());
		byte[] ltpa = Base64.decodeBase64(ltpaToken.getBytes());
		ByteArrayInputStream stream = new ByteArrayInputStream(ltpa);
		int usernameLength = ltpa.length - 40;
		byte header[] = new byte[4];
		byte creation[] = new byte[8];
		byte expires[] = new byte[8];
		byte username[] = new byte[usernameLength];
		byte[] sha = new byte[20];
		// 读取LTPAToken版本号
		stream.read(header, 0, 4);
		if (header[0] != 0 || header[1] != 1 || header[2] != 2
				|| header[3] != 3)
			throw new IllegalArgumentException("Invalid ltpaToken format");
		// 读取开始时间
		stream.read(creation, 0, 8);
		// 读取到期时间
		stream.read(expires, 0, 8);
		// 读取Domino用户DN
		stream.read(username, 0, usernameLength);
		// 读取SHA校验和
		stream.read(sha, 0, 20);
		// 转换用户名
		char characters[] = new char[usernameLength];
		String dn;
		Date creationDate;
		Date expiresDate;
		try {
			InputStreamReader isr = new InputStreamReader(
					new ByteArrayInputStream(username), CHARSET);
			isr.read(characters);

			// 获得Domino用户DN
			dn = new String(characters);
			// 获得创建时间
			creationDate = new Date(
					Long.parseLong(new String(creation), 16) * 1000);
			// 获得到期时间
			expiresDate = new Date(
					Long.parseLong(new String(expires), 16) * 1000);
		} catch (Exception e) {
			throw new Exception(e);
		}


		// 创建LTPA Token
		ByteArrayOutputStream ostream = new ByteArrayOutputStream();
		try {
			// LTPA Token版本号
			ostream.write(header);
			// 创建时间
			ostream.write(creation);
			// 过期时间
			ostream.write(expires);
			// Domino用户DN，如CN=SquallZhong/O=DigiWin
			ostream.write(username);
			// Domino LTPA 密钥
			ostream.write(dominoSecret);
			ostream.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		// 进行 SHA-1 校验和
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("SHA-1");
			md.reset();
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
		byte[] digest = md.digest(ostream.toByteArray());
		// 完成 SHA-1 校验和，digest长度为20
		return MessageDigest.isEqual(digest, sha);
	}
}
